#!/usr/bin/env python3.1
# bookstat.py
# programmed by ryuchihoon
# used with python3.1

import sys
import urllib.request
import urllib.error
import re

# dict that keeps NAME:BOOKSET info
stat = {}

if len(sys.argv) == 2:
	server = sys.argv[1]
else:
	# bookstatserver should be specified at '/etc/hosts'
	server = "bookstatserver"

urladdr = "http://" + server + "/zbxe/book_collection/"

print("getting " + urladdr)
try:
	global f
	f = urllib.request.urlopen(urladdr)
except urllib.error.URLError:
	print("Can not connect to " + urladdr)
	quit(1)

s = re.search(r'/page/(\d+)" class="goToLast">', f.read().decode())
if s == None:
	print("Can not find max page information.")
	quit(1)

maxpage = int(s.group(1))
print("Total page count : {0}".format(maxpage))

for pageNum in range(1,maxpage+1):
	pagepath = "page/{0}".format(pageNum)
	try:
		pageaddr = urladdr + pagepath
		print("\ngetting " + pageaddr)
		f = urllib.request.urlopen(pageaddr).read().decode()
		print("----- page {0} -----".format(pageNum))
		# print(f)

		# find book block
		cc = re.compile(
			r'<table [^>]*class="boardList">.*?<tbody>(.*?)</tbody>',
			re.DOTALL)
		ss = cc.search(f)
		if ss == None:
			print("Can not find book list on this page")
			continue

		bookblock = ss.group(1)
		# print(bookblock)

		# find book items
		bookiter = re.compile(
			r'<tr class="([^"]*)">.*?<a href=".*?/zbxe/book_collection/(\d*).*?">(.*?)</a>.*?</tr>',
			re.DOTALL).finditer(bookblock)
		for bookmatch in bookiter:
			# print(bookmatch.group(0))
			bookclass = bookmatch.group(1)
			booknumber = bookmatch.group(2)
			book = bookmatch.group(3)
			# print(bookclass,booknumber,book)
			if bookclass == 'notice':
				continue

			print(booknumber, book)

			# connect to book item page
			bookurladdr = urladdr + booknumber
			# print(bookurladdr)

			# borrower list
			borrowerset = set()

			try:
				bf = urllib.request.urlopen(bookurladdr).read().decode()
				# print(bf)

				# find reply block
				bcc = re.compile(
					r'<div class="replyItem ">.*?<div class="author">(.*?)</div>',
					re.DOTALL)
				replyiter = bcc.finditer(bf)
				for replymatch in replyiter:
					borrower = replymatch.group(1).strip()

					#remove any html tag
					borrower = re.sub(r'<.*>', '', borrower)

					if borrower not in stat:
						stat[borrower] = set()
					stat[borrower].add(book)

					borrowerset.add(borrower)	

			except urllib.error.URLError:
				continue

			if len(borrowerset) > 0:
				print(r' * ' +  ', '.join(list(borrowerset)))

	except urllib.error.URLError:
		quit(0)

# show stat
print('\n' + '='*30 + '\nBook borrower ranking\n' + '='*30)
def sortfunc(key):
	return len(stat[key])
for key in sorted(stat.keys(), key=sortfunc, reverse=True):
	print("{0}<{1}> : {2}".format(key, len(stat[key]), stat[key]))
